package com.example.vv.service;

public class TablePrinter {
    public static void main(String[] args) {
        // 表头
        String[] headers = {"ID", "Name", "Age"};

        // 表数据
        String[][] data = {
            {"1", "Alice", "23"},
            {"2", "Bob", "34"},
            {"3", "张三", "28"},
            {"4", "Jonathan Archer", "45"},
            {"5", "李四", "30"},
            {"6", "王五六七八九十", "35"}
        };

        // 计算每列的最大宽度
        int[] columnWidths = calculateColumnWidths(headers, data);

        // 打印表头
        printRow(headers, columnWidths);
        printLine(columnWidths);

        // 打印表数据
        for (String[] row : data) {
            printRow(row, columnWidths);
        }
    }

    private static int getStringDisplayWidth(String str) {
        int width = 0;
        for (char ch : str.toCharArray()) {
            // 判断是否是汉字或全角字符
            if (Character.UnicodeScript.of(ch) == Character.UnicodeScript.HAN
                    || Character.UnicodeBlock.of(ch) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                    || Character.UnicodeBlock.of(ch) == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) {
                width += 2;
            } else {
                width += 1;
            }
        }
        return width;
    }

    private static int[] calculateColumnWidths(String[] headers, String[][] data) {
        int[] widths = new int[headers.length];

        // 初始化宽度为表头宽度
        for (int i = 0; i < headers.length; i++) {
            widths[i] = getStringDisplayWidth(headers[i]);
        }

        // 遍历数据，更新列宽度
        for (String[] row : data) {
            for (int i = 0; i < row.length; i++) {
                int cellWidth = getStringDisplayWidth(row[i]);
                if (cellWidth > widths[i]) {
                    widths[i] = cellWidth;
                }
            }
        }

        // 为每列增加额外宽度，保证视觉上的更美观
        for (int i = 0; i < widths.length; i++) {
            widths[i] += 2; // 额外添加2个字符的宽度
        }

        return widths;
    }

    private static void printRow(String[] row, int[] columnWidths) {
        for (int i = 0; i < row.length; i++) {
            int displayWidth = getStringDisplayWidth(row[i]);
            int padding = columnWidths[i] - displayWidth;
            System.out.print(row[i]);
            for (int j = 0; j <= padding; j++) {
                System.out.print(" ");
            }
        }
        System.out.println();
    }

    private static void printLine(int[] columnWidths) {
        for (int width : columnWidths) {
            for (int i = 0; i < width; i++) {
                System.out.print("-");
            }
            System.out.print(" ");
        }
        System.out.println();
    }
}
